iT邦幫忙

2024 iThome 鐵人賽

DAY 9
1

函數

函數的創建與調用

方法定義

方法定義在對象字面量中定義函數,白話一點就是在一個變量中直接在中定義一個方法。這種語法是在ES6中引入的,它提供了一種更簡潔的方法來定義對象。


let person = { 
    name: "Alice", 
    greet() { 
        console.log(`Hello, my name is ${this.name}`); 
    } 
}; 
person.greet(); // 輸出:Hello, my name is Alice 
![](http://)

在這個例子中,greet就是直接在person對象中定義的方法。

  • 除此之外,他還可以在一個對象中定義多個方法。
let calculator = { 
    add(a, b) { 
        return a + b; 
    }, 
    subtract(a, b) { 

        return a - b; 
    }, 
    multiply(a, b) { 
        return a * b; 
    }, 
    divide(a, b) { 
        return a / b; 
    } 
}; 

console.log(calculator.add(5, 3));      // 輸出:8 
console.log(calculator.subtract(10, 4)); // 輸出:6 
console.log(calculator.multiply(2, 6)); // 輸出:12 
console.log(calculator.divide(15, 3));  // 輸出:5 
  • ES6還允許我們使用計算屬性名來定義方法:
let methodName = "sayHello";
let greeter = { 
    [methodName]() { 
        console.log("Hello!"); 
    } 
}; 

greeter.sayHello(); // 輸出:Hello! 

這就使得我們可以動態地定義方法名。

綜上所述,方法定義帶來了這些優點:

  • 簡潔的語法:比傳統的key: function() {}語法更簡潔。
  • 自動綁定this:方法中的this自動綁定到對象實例。
  • 代碼組織:將相關的方法和數據組織在一起,提高代碼的可讀性和維護性。
  • 封裝:可以實現簡單的對象封裝,將數據和行為綑綁在一起。

不過這種方法定義方式與傳統的對象.方法 =function() {}方式在功能上是完全等價的,主要區別在於語法的簡潔性和代碼的組織方式。

構造函數

構造函數是JavaScript中用於創建對象的一種特殊函數。它是實現面向對象編程的一種方式,允許我們創建具有相同結構和行為的多個對象實例。
1.基本用法

//基本語法
function ConstructorName(parameter1, parameter2, ...) {
    this.property1 = parameter1;
    this.property2 = parameter2;
    // ...
    this.method = function() {
        // 方法定義
    };
}

例子:

function Person(name, age) {
    this.name = name;
    this.age = age;
    this.sayHello = function() {
        console.log(Hello, my name is ${this.name} and I'm ${this.age} years old.);
    };
}

let person1 = new Person("Alice", 30);
let person2 = new Person("Bob", 25);

person1.sayHello(); // 輸出:Hello, my name is Alice and I'm 30 years old.
person2.sayHello(); // 輸出:Hello, my name is Bob and I'm 25 years old.

**構造函數通常與'new'一起使用,其特點為:

  • 創建一個新的空對象
  • 將這個對象的原型設置為構造函數的prototype屬性
  • 將構造函數中的this綁定到新創建的對象
  • 執行構造函數中的代碼
  • 如果構造函數沒有顯式返回對象,則返回新創建的對象
  1. 添加方法:
    除了能在構造函數內部定義,它也可以添加在原形上

例子:

function Car(make, model) {
    this.make = make;
    this.model = model;
}

// 添加到原型
Car.prototype.getInfo = function() {
    return ${this.make} ${this.model};
};

let myCar = new Car("Toyota", "Corolla");
console.log(myCar.getInfo()); // 輸出:Toyota Corolla
  1. 私有變量及閉包
    可以使用閉包來創建私有變量:
function Counter() {
    let count = 0; // 私有變量

    this.increment = function() {
        return ++count;
    };

    this.decrement = function() {
        return --count;
    };
}

let counter = new Counter();
console.log(counter.increment()); // 輸出:1
console.log(counter.increment()); // 輸出:2
console.log(counter.decrement()); // 輸出:1
console.log(counter.count); // 輸出:undefined(無法直接訪問count)

4.構造函數的返回值:
通常,構造函數不需要顯式的return語句。但如果有return語句的出現,則:

  • 如果 return 後面跟著一個對象,則返回該對象
  • 如果 return 後面跟著原始類型,則忽略該 return 語句,返回新創建的對象
function SpecialObject(value) {
    this.value = value;

    return { custom: "Custom Object" };
}

let obj = new SpecialObject(100);
console.log(obj.custom); // 輸出:Custom Object
console.log(obj.value);  // 輸出:undefined

5.檢查對象類型:
可以使用instance of運算符檢查對象是否是某個構造函數的實例:

javascriptCopyfunction Animal(name) {
    this.name = name;
}

let cat = new Animal("Whiskers");

console.log(cat instanceof Animal); // 輸出:true
console.log(cat instanceof Object); // 輸出:true

6.構造函數的問題和解決方案:
每次創建新實例時,構造函數內部定義的方法都會被重新創建,這樣可能會導致內存浪費。解決方法是將方法定義在原型上:

javascriptCopyfunction Dog(name) {
    this.name = name;
}

Dog.prototype.bark = function() {
    console.log(${this.name} says Woof!);
};

let dog1 = new Dog("Rex");
let dog2 = new Dog("Buddy");

dog1.bark(); // 輸出:Rex says Woof!
dog2.bark(); // 輸出:Buddy says Woof!

console.log(dog1.bark === dog2.bark); // 輸出:true(共享同一個方法)

7.ES6 類語法:
ES6 引入了 class 語法,提供了一種更清晰的方式來創建構造函數和原型方法:

class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    sayHello() {
        console.log(Hello, my name is ${this.name} and I'm ${this.age} years old.);
    }
}

let person = new Person("Alice", 30);
person.sayHello(); // 輸出:Hello, my name is Alice and I'm 30 years old.

開始上課了沒什麼時間,希望不會拖延太多,明天應該可以結束


上一篇
d8 函數(上)
下一篇
d10 函數(完)
系列文
javascript基礎自學及各工具應用了解26
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言